// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TransactionEditorViewModel.cs" company="Concept Architecture">
//   (c) 2010 Muhammad Umer Farooq
// </copyright>
// <summary>
//   Defines the  type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Hisaab.Client.Modules.Core.Transaction.ViewModel
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media.Imaging;

    using Hisaab.Business.Interfaces;
    using Hisaab.Client.Common.BaseClasses;
    using Hisaab.Client.Common.Services;
    using Hisaab.Common;

    using Microsoft.Practices.Prism.Commands;
    using Microsoft.Practices.Prism.Regions;
    using Microsoft.Practices.ServiceLocation;

    using Account = Hisaab.Client.Model.Account;
    using Tag = Hisaab.Client.Model.Tag;
    using Transaction = Hisaab.Client.Model.Transaction;
    using TransactionTypes = Hisaab.Client.Model.TransactionTypes;

    /// <summary>
    /// Defines the <seealso cref="TransactionEditorViewModel"/> type.
    /// </summary>
    public class TransactionEditorViewModel : WindowViewModel, INavigationAware
    {
        #region Data Members

        /// <summary>
        /// Account object
        /// </summary>
        private readonly ITransactionManager _transactionManager;

        /// <summary>
        /// Account manager
        /// </summary>
        private readonly IAccountManager _accountManager;

        /// <summary>
        /// Tag Manager
        /// </summary>
        private readonly ITagManager _tagManager;

        /// <summary>
        /// The Session Manager
        /// </summary>
        private readonly ISession _session;

        /// <summary>
        /// Member variable _saveCommand
        /// </summary>
        private ICommand _saveCommand;

        /// <summary>
        /// Transaction types
        /// </summary>
        private ObservableCollection<KeyValuePair<TransactionTypes, string>> _transactionTypes;

        /// <summary>
        /// Accounts list
        /// </summary>
        private ObservableCollection<Account> _accounts;

        /// <summary>
        /// Selected transaction
        /// </summary>
        private Transaction _selectedTransaction;

        /// <summary>
        /// Member variable _isNewTransaction
        /// </summary>
        private bool _isNewTransaction;

        /// <summary>
        /// The tags collection
        /// </summary>
        private ObservableCollection<Tag> _tags;

        #endregion Data Members

        #region Constructors and Initializers

        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionEditorViewModel"/> class.
        /// </summary>
        public TransactionEditorViewModel()
            : this(
                ServiceLocator.Current.GetInstance<ITransactionManager>(),
                ServiceLocator.Current.GetInstance<IAccountManager>(),
                ServiceLocator.Current.GetInstance<ITagManager>(),
                ServiceLocator.Current.GetInstance<ISession>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionEditorViewModel"/> class.
        /// </summary>
        /// <param name="transactionManager">The transaction manager.</param>
        /// <param name="accountManager">The account manager</param>
        /// <param name="tagManager">The tag Manager</param>
        /// <param name="session">The session</param>
        public TransactionEditorViewModel(
            ITransactionManager transactionManager,
            IAccountManager accountManager,
            ITagManager tagManager,
            ISession session)
        {
            Contract.Requires<ArgumentNullException>(transactionManager != null);
            Contract.Requires<ArgumentNullException>(accountManager != null);
            Contract.Requires<ArgumentNullException>(tagManager != null);
            Contract.Requires<ArgumentNullException>(session != null);

            Title = "Transaction Editor";
            Icon = new BitmapImage(new Uri("pack://application:,,,/Hisaab.Client.Common;component/Resources/Images/16/TransactionGreen.png"));

            _transactionManager = transactionManager;
            _accountManager = accountManager;
            _tagManager = tagManager;
            _session = session;
        }

        #endregion Constructors and Initializers

        #region Properties

        /// <summary>
        /// Gets the transactions.
        /// </summary>
        public IEnumerable<Transaction> Transactions
        {
            get
            {
                return _transactionManager
                    .List()
                    .Select(x => x.Map<Business.Entities.Transaction, Transaction>());
            }
        }

        /// <summary>
        /// Gets the Account Types.
        /// </summary>
        /// <value>
        /// The transaction types.
        /// </value>
        public ObservableCollection<KeyValuePair<TransactionTypes, string>> TransactionTypes
        {
            get
            {
                if (_transactionTypes == null)
                {
                    LoadTransactionTypes();
                }

                return _transactionTypes;
            }

            private set
            {
                RaisePropertyChangingEvent("TransactionTypes");
                _transactionTypes = value;
                RaisePropertyChangedEvent("TransactionTypes");
            }
        }

        /// <summary>
        /// Gets the Account Types.
        /// </summary>
        public ObservableCollection<Account> Accounts
        {
            get
            {
                if (_accounts == null)
                {
                    _accounts = new ObservableCollection<Account>(
                        _accountManager
                            .List(new Business.Entities.Account { UserId = _session.LoggedUser })
                            .OrderBy(x => x.Name)
                            .Select(x => x.Map<Business.Entities.Account, Account>()));
                }

                return _accounts;
            }
        }

        /// <summary>
        /// Gets the tags.
        /// </summary>
        public ObservableCollection<Tag> Tags
        {
            get
            {
                if (_tags == null)
                {
                    _tags = new ObservableCollection<Tag>(
                        _tagManager
                            .List(new Business.Entities.Tag { UserId = _session.LoggedUser })
                            .OrderBy(x => x.Name)
                            .Select(x => x.Map<Business.Entities.Tag, Tag>()));
                }

                return _tags;
            }
        }

        /// <summary>
        /// Gets or sets the selected transaction.
        /// </summary>
        /// <value>
        /// The selected transaction.
        /// </value>
        public Transaction SelectedTransaction
        {
            get
            {
                return _selectedTransaction;
            }

            set
            {
                RaisePropertyChangingEvent("SelectedTransaction");
                _selectedTransaction = value;
                RaisePropertyChangedEvent("SelectedTransaction");
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether [new account].
        /// </summary>
        /// <value>
        /// True if new account; otherwise, false.
        /// </value>
        public bool IsNewTransaction
        {
            get
            {
                return _isNewTransaction;
            }

            set
            {
                RaisePropertyChangingEvent("IsNewTransaction");
                _isNewTransaction = value;
                RaisePropertyChangedEvent("IsNewTransaction");
            }
        }

        /// <summary>
        /// Gets the dialog type string.
        /// </summary>
        /// <value>
        /// The dialog type string.
        /// </value>
        public string DialogTypeString
        {
            get
            {
                return IsNewTransaction ? "Add" : "Edit";
            }
        }

        /// <summary>
        /// Gets the save command.
        /// </summary>
        public ICommand SaveCommand
        {
            get
            {
                if (_saveCommand == null)
                {
                    _saveCommand = new DelegateCommand(SaveTransaction, CanSaveTransaction);
                }

                return _saveCommand;
            }
        }

        #endregion Properties

        #region Public Methods

        /// <summary>
        /// Saves the transaction.
        /// </summary>
        public void SaveTransaction()
        {
            try
            {
                if (IsNewTransaction)
                {
                    int id =
                        _transactionManager.Add(SelectedTransaction.Map<Transaction, Business.Entities.Transaction>());
                    IsNewTransaction = false;
                    SelectedTransaction.TransactionId = id;
                }
                else
                {
                    _transactionManager.Update(SelectedTransaction.Map<Transaction, Business.Entities.Transaction>());
                }

                ServiceLocator.Current.GetInstance<IMessageBoxService>()
                    .Show("Transaction saved successfully", "Hisaab", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                ServiceLocator.Current.GetInstance<IMessageBoxService>()
                    .Show("Failure saving data" + Environment.NewLine + ex.Message, "Hisaab", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        /// <summary>
        /// Determines whether this instance [can save transaction] the specified obj.
        /// </summary>
        /// <returns>
        /// True if this instance can save transaction the specified obj; otherwise, false.
        /// </returns>
        public bool CanSaveTransaction()
        {
            return true;
        }

        #endregion Public Methods

        #region Implementation of INavigationAware

        /// <summary>
        /// Called when [navigated to].
        /// </summary>
        /// <param name="navigationContext">The navigation context.</param>
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters["ID"] != null)
            {
                IsNewTransaction = false;
                int id = int.Parse(navigationContext.Parameters["ID"]);
                SelectedTransaction = _transactionManager.GetById(id).Map<Business.Entities.Transaction, Transaction>();
            }
            else
            {
                var type = Model.TransactionTypes.Expanse;
                if (navigationContext.Parameters["Type"] != null)
                {
                    Enum.TryParse(navigationContext.Parameters["Type"], out type);
                }

                IsNewTransaction = true;
                SelectedTransaction = new Transaction
                    {
                        Date = DateTime.Today,
                        LinkedTransactionDate = DateTime.Today,
                        Tags = new List<Tag>(),
                        TransactionType = type,
                        IsTransferTransaction = type == Model.TransactionTypes.Transfer
                    };
                LoadTransactionTypes();
            }

            SelectedTransaction.Dirty = false;
        }

        /// <summary>
        /// Determines whether [is navigation target] [the specified navigation context].
        /// </summary>
        /// <param name="navigationContext">The navigation context.</param>
        /// <returns>
        ///   <c>true</c> if [is navigation target] [the specified navigation context]; otherwise, <c>false</c>.
        /// </returns>
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters["ID"] != null)
            {
                int id = int.Parse(navigationContext.Parameters["ID"]);
                return id == SelectedTransaction.TransactionId;
            }

            return false;
        }

        /// <summary>
        /// Called when [navigated from].
        /// </summary>
        /// <param name="navigationContext">The navigation context.</param>
        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }

        /// <summary>
        /// Loads the transaction types.
        /// </summary>
        private void LoadTransactionTypes()
        {
            var types = new List<KeyValuePair<TransactionTypes, string>>
                {
                    new KeyValuePair<TransactionTypes, string>(Model.TransactionTypes.Expanse, "Expanse"),
                    new KeyValuePair<TransactionTypes, string>(Model.TransactionTypes.Income, "Income")
                };
            if (IsNewTransaction)
            {
                types.Add(new KeyValuePair<TransactionTypes, string>(Model.TransactionTypes.Transfer, "Transfer"));
            }

            TransactionTypes = new ObservableCollection<KeyValuePair<TransactionTypes, string>>(types);
        }

        #endregion Implementation of INavigationAware
    }
}